package com.wx.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CalculateHandlerInvokeTimeInterceptor implements HandlerInterceptor {
	
	private static final String START = "start";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		long start = System.currentTimeMillis();
		request.setAttribute(START, start);
		System.out.println("[ " + request.getRequestURI() + " ] 请求到达");
		// TODO: 这个方法应该返回 true，允许 DispatcherServlet 继续处理请求。
		//  否则，DispatcherServlet 会认为这个方法已经处理了请求，直接将响应返回给用户。
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		long end = System.currentTimeMillis();
		long start = (long) request.getAttribute(START);
		long spendTime = end -start;

		// TODO: 如果使用了缓存处理 (Last-Modified)，这里返回的 modelANDView 为 null，所以需要进行判断，否则 NullPointerException
		if (modelAndView != null) {
			modelAndView.addObject("spendTime", spendTime);
		}

		if (spendTime > 300) {
			System.out.println("执行方法超时，耗时: " + spendTime);
		} else {
			System.out.println("执行方法正常，耗时: " + spendTime);
		}
	}

}
